<template>
	<view class="defect-state-picker row full-width input">
		<picker class="flex1" @change="handlePickerChange" :value="activeIndex" range-key="itemName" :range="list">
			<view v-if="isShowClearButton" class="full-width input-text">{{activeStateName}}</view>
			<text v-else class="full-width input-text placeholder">{{placeholderText}}</text>
		</picker>
		<uni-icons v-show="isShowClearButton" type="clear" size="25" color="#c0c4cc" @click="handleResetClick"></uni-icons>
	</view>
</template>

<script>
	export default {
		name: 'DefectStatePicker',
		model: {
			prop: 'defectState',
			event: 'input'
		},
		data() {
			return {
				activeIndex: null
			}
		},
		props: {
			/** 当前选中的状态索引集合 */
			defectState: {
			  type: String,
			  default: null
			},
			/** 状态集合 */
			stateList: {
				type: Array,
				default: ()=>[]
			},
			/** 状态对象中显示名字的属性key */
			labelName: {
				type: String,
				default: 'value'
			},
			/** 提示 */
			placeholder: {
				type: String,
				default: null
			}
		},
		computed: {
			/** 选择的类型名称显示名称 */
			activeStateName: function() {
				const defectState = (this.activeIndex>=0 && this.stateList.length>0)?this.list[this.activeIndex]:null;
				return defectState?defectState.itemName:'';
			},
			/** 可选择的类型集合 */
			list() {
				return this.stateList.map(t=>{
					t.itemName = this.$i18n.t(t[this.labelName]);
					return t;
				})
			},
			/** 是否显示清空按钮  */
			isShowClearButton() {
				return this.stateList.length>0 && this.activeStateName;
			},
			/** placeholder显示文本  */
			placeholderText() {
				return this.placeholder || this.$i18n.t('defect.select-state');
			}
		},
		created() {
			// 设置当前选中的索引值
			if(this.defectState && this.defectState.length>0) {
				this.activeIndex = this.defectState.split(',')[0];
			}
		},
		methods: {
			/** 重设 */
			handleResetClick(e) {
				this.activeIndex = -1;
				this.emit();
			},
			/**处理等级选择改变 */
			handlePickerChange(e) {
				this.activeIndex = e.detail.value;
				this.emit();
			},
			/** 更新父组件传递的v-model */
			emit() {
				if(this.activeIndex>=0 && this.stateList.length>0) {
					this.$emit('input', this.activeIndex);
				} else {
					this.$emit('input', null);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.defect-state-picker {
		justify-content: flex-end;
		padding-left: 20rpx;
	}
</style>